using System;

using Dashboard;
using Dashboard.Util;

namespace Dashboard.Mint.Actions {
	
	[Action (Type = "db:file")]
	public class FileOpenAction : Action {

		public FileOpenAction ()
		{
			Name = "Open";
			Description = "Open file with default application";
		}

		public override void Execute (Match match)
		{
			string command = null, item;
			bool expects_uris = false;

			string mime_type = match.Properties.GetPropertyValue ("db:mimetype");

			if (String.IsNullOrEmpty (mime_type)) {
				Console.WriteLine ("mimetype is empty");
				return;
			}

			// FIXME: This is evil.  Nautilus should be handling
			// inode/directory, not just x-directory/normal
			if (mime_type == "inode/directory")
				mime_type = "x-directory/normal";
			
#if ENABLE_DESKTOP_LAUNCH
			command = "desktop-launch";
			expects_uris = true;
#else
			Gnome.Vfs.MimeApplication app = GnomeFu.GetDefaultAction (mime_type);
			if (app.Exec != null) {
				command = app.Exec;
				expects_uris = app.SupportsUris ();
			}
#endif                  
			if (command == null) {
				Console.WriteLine ("Can't open MimeType '{0}'", mime_type);
				return;
			}
			
			if (expects_uris)
				item = match.Uri.ToString ();
			else
				item = match.Uri.LocalPath;
			
			// Sometimes the command is 'quoted'
			if (command.IndexOf ('\'') == 0 && command.LastIndexOf ('\'') == command.Length - 1)
				command = command.Trim ('\'');
			
			// This won't work if a program really has a space in
			// the command filename, but I think other things would
			// break with that too, and in practice it doesn't seem to
			// happen.
			//
			// A bigger issue is that the arguments are split up by
			// spaces, so quotation marks used to indicate a single
			// entry in the argv won't work.  This probably should
			// be fixed.
			string[] arguments = null;
			int idx = command.IndexOf (' ');
			if (idx != -1) {
				arguments = command.Substring (idx + 1).Split (' ');
				command = command.Substring (0, idx);
			}
			
			string[] argv;
			if (arguments == null)
				argv = new string [] { command, item };
			else {
				argv = new string [arguments.Length + 2];
				argv [0] = command;
				argv [argv.Length - 1] = item;
				Array.Copy (arguments, 0, argv, 1, arguments.Length);
			}
			
			Console.WriteLine ("Cmd: {0}", command);
			Console.WriteLine ("Arg: {0}", String.Join (" ", argv, 1, argv.Length - 2));
			Console.WriteLine ("Itm: {0}", item);
			
			SafeProcess p = new SafeProcess ();
			p.Arguments = argv;
			
			try {
				p.Start ();
			} catch (Exception e) {
				Console.WriteLine ("Error in OpenFromMime: " + e);
			}
		}
	}
}